﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;
using System.Diagnostics;
using System.Configuration;

using SAW_Core;
using WLMCoreLibrary;

namespace SAW
{
    public partial class ModuloAdministracion : System.Web.UI.Page
    {
        dbConnector ConexionDB;
        protected override void OnUnload(EventArgs e)
        {
            //ConexionDB.CloseConnection();
            base.OnUnload(e);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            ConexionDB = new dbConnector();
            FuncionesLocales.CheckPagePermision(ref ConexionDB);
            FuncionesLocales.ManejarMensaje();

            if (Request.QueryString["listadousuarios"] != null)
            {
                panelAdminCategorias.Visible = false;
                panelAdminUsuarios.Visible = true;
            }
            
            if (Request.QueryString["addUsuario"] != null ||Request.QueryString["editUsuario"] != null)
            {
                panelAdminCategorias.Visible = false;
                panelAltaUsuario.Visible = true;
                botonBorrarUsuario.Enabled = true;
                botonGuardarUsuario.Enabled = true;

            }

            if (Request.QueryString["listado"] != null)
            {
                if (Request.QueryString["categoriasclientes"] != null)
                    ListadoJSONAdministracion("SELECT id,NombreCategoria FROM CLIENTESCATEGORIAS ");
                if (Request.QueryString["categoriasproductos"] != null)
                    ListadoJSONAdministracion("SELECT id,NombreCategoria FROM PRODUCTOCATEGORIA ");
                if (Request.QueryString["lineas"] != null)
                    ListadoJSONAdministracion("SELECT id,NombreLINEA FROM PRODUCTOLINEA ");
                if (Request.QueryString["marcas"] != null)
                    ListadoJSONAdministracion("SELECT id,NombreMarca FROM PRODUCTOMARCA ");

            }

            if (Request.QueryString["respaldarDB"] != null)
                RespaldarDB();
        }


        protected void ListadoJSONCuentas()
        {

            string FieldList = "SELECT U.id,nombre,cuenta,Alias,CONCAT('$ ',CAST(Format(SaldoActual,2) AS CHAR)) as SaldoActuala,numeroUltimoCheque FROM USUARIOS U ";
            int dataPage = Convert.ToInt32(Request["page"]);
            int rowsPerPage = Convert.ToInt32(Request["rp"]);
            string sortname = Request["sortname"];
            string sortorder = Request["sortorder"];
            if (sortname == null) sortname = "id";
            if (sortorder == null) sortorder = "desc";
            string sort = "ORDER BY " + sortname + " " + sortorder;
            if (dataPage == 0) dataPage = 1;
            if (rowsPerPage == 0) rowsPerPage = 50;
            int start = ((dataPage - 1) * rowsPerPage);
            string where = "";
            string qtype = Request["qtype"];
            where = "";
            string limit = "LIMIT " + start + ", " + rowsPerPage;

            string strCommand = FieldList + where + sort + " " + limit;

            WLMFunctions.JsonGrid(strCommand, FieldList, where, dataPage);

        }


        protected void ListadoJSONAdministracion(string FieldList)
        {

            int dataPage = Convert.ToInt32(Request["page"]);
            int rowsPerPage = Convert.ToInt32(Request["rp"]);
            string sortname = Request["sortname"];
            string sortorder = Request["sortorder"];
            if (sortname == null) sortname = "id";
            if (sortorder == null) sortorder = "desc";
            string sort = "ORDER BY " + sortname + " " + sortorder;
            if (dataPage == 0) dataPage = 1;
            if (rowsPerPage == 0) rowsPerPage = 50;
            int start = ((dataPage - 1) * rowsPerPage);
            string where = "";
            string qtype = Request["qtype"];
            where = "";
            string limit = "LIMIT " + start + ", " + rowsPerPage;

            string strCommand = FieldList + where + sort + " " + limit;

            WLMFunctions.JsonGrid(strCommand, FieldList, where, dataPage);

        }

        
        protected void RespaldarDB()
    {
            try
            {
                DateTime backupTime = DateTime.Now;
                int year = backupTime.Year;
                int month = backupTime.Month;
                int day = backupTime.Day;
                int hour = backupTime.Hour;
                int minute = backupTime.Minute;
                int second = backupTime.Second;
                int ms = backupTime.Millisecond;

                String tmestr = backupTime.ToString();
                System.IO.DirectoryInfo directorio = new System.IO.DirectoryInfo(ConfigurationManager.AppSettings["PathRespaldo"]);
                if (!directorio.Exists)
                    directorio.Create();
                tmestr = ConfigurationManager.AppSettings["PathRespaldo"] + ConfigurationManager.AppSettings["DBName"]+"-" + year + month.ToString("00") + day.ToString("00") + "-" + hour.ToString("00") + minute.ToString("00") + second.ToString("00") + ".sql";
                StreamWriter file = new StreamWriter(tmestr);
                ProcessStartInfo proc = new ProcessStartInfo();
                proc.FileName = "mysqldump";
                proc.RedirectStandardInput = false;
                proc.RedirectStandardOutput = true;
                proc.UseShellExecute = false;
                proc.Arguments = ConfigurationManager.AppSettings["DBName"]+" --password=" + ConfigurationManager.AppSettings["DBPass"] + " --user=" + ConfigurationManager.AppSettings["DBUser"] + "";
                
                Process p = Process.Start(proc);
                string res;
                res = p.StandardOutput.ReadToEnd();
                file.WriteLine(res);
                p.WaitForExit();
                file.Close();

                System.IO.FileInfo file1 = new System.IO.FileInfo(tmestr);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file1.FullName);
                HttpContext.Current.Response.AddHeader("Content-Length", file1.Length.ToString());
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.WriteFile(file1.FullName);
                //file.Delete();
                ConexionDB.CloseConnection();
                HttpContext.Current.Response.End();
                
            }

            catch (IOException ex)
            {
                Response.Write("Disk full or other IO error , unable to backup!");
            }
        }

        protected void botonGuardarUsuario_Click(object sender, EventArgs e)
        {
             MiWebSiteUser usuario;
            if (idUsuarioActual.Value == "0")
                usuario = new MiWebSiteUser(ref ConexionDB);
            else
                usuario = new MiWebSiteUser(Convert.ToInt32(idUsuarioActual.Value),ref ConexionDB);
            usuario.username = UserName.Text;
            usuario.password = Password.Text;
            usuario.email = Email.Text;
            usuario.nombre = Nombre.Text;
            usuario.apellidos = Apellidos.Text;
            if(esVendedor.Checked)
                usuario.newsletter =1;
            else
                usuario.newsletter = 0;
            usuario.Save();
            ConexionDB.CloseConnection();
            Response.Redirect("/ModuloAdministracion.aspx?listadousuarios=true&mensaje=El usuario " + usuario.username + " fue dado de alta correctamente en el sistema");
        }

        protected void botonBorrarUsuario_Click(object sender, EventArgs e)
        {
           
        }


    }
}